package br.com.massai.model.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "ACCESS_CONTROL", uniqueConstraints = @UniqueConstraint(columnNames={"LAST_ACCESS", "LOCATION_ACCESS", "USER_ID"}))
@NamedQueries({
	@NamedQuery(name = "AccessControl.lastAccess", query = "SELECT a FROM AccessControl a WHERE a.id = (SELECT MAX(a2.id) FROM AccessControl a2 WHERE a2.user =:user)"),
	@NamedQuery(name = "AccessControl.duplicate", query = "SELECT COUNT(a) FROM AccessControl a WHERE a.lastAccess =:lastAccess AND a.locationAccess =:locationAccess AND a.user =:user")
})
public class AccessControl extends GenericEntity {

	private static final long serialVersionUID = 2710600328085054250L;

	@Id
	@SequenceGenerator(name = "seqAccessControl", sequenceName = "seq_access_control", allocationSize = 1)
	@GeneratedValue(generator = "seqAccessControl", strategy = GenerationType.SEQUENCE)
	private Long id;

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "LAST_ACCESS", nullable = false)
	private Date lastAccess;

	@Column(name = "LOCATION_ACCESS", nullable = false, length = 15, columnDefinition = "VARCHAR(15)")
	private String locationAccess;

	@ManyToOne(fetch = FetchType.LAZY, optional = false)
	private Collaborator user;
	
	public AccessControl() { }
	
	public AccessControl(String ip, Date lastAccess, Collaborator user) {
		this();
		this.locationAccess = ip;
		this.lastAccess = lastAccess;
		this.user = user;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Date getLastAccess() {
		return lastAccess;
	}

	public void setLastAccess(Date lastAccess) {
		this.lastAccess = lastAccess;
	}

	public String getLocationAccess() {
		return locationAccess;
	}

	public void setLocationAccess(String locationAccess) {
		this.locationAccess = locationAccess;
	}

	public Collaborator getUser() {
		return user;
	}

	public void setUser(Collaborator user) {
		this.user = user;
	}
}